package tool

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"regexp"
	"strconv"
	"strings"
	"time"
)

func CheckErr(err error) {
	if err != nil {
		panic(err)
	}
}

func IntToString(num interface{}) string {
	return fmt.Sprintf("%v", num)
}

func GetRandom() string {
	rand.Seed(time.Now().Unix())
	str := strconv.Itoa(rand.Int())
	return fmt.Sprintf("%v", str[0:9])
}

func GetRandom4() string {
	rand.Seed(time.Now().Unix())
	str := strconv.Itoa(rand.Int())
	return fmt.Sprintf("%v", str[0:4])
}

func GetDeviceID() string {
	rand.Seed(time.Now().Unix())
	str := strconv.Itoa(rand.Int())
	for len(str) < 18 {
		str += str
	}
	return "e" + str[2:17]
}

func GetByRegexp(str string, pre string) string {
	pat := pre + "[a-zA-Z0-9-/_·=:?@.&]+"
	re := regexp.MustCompile(pat)
	result := re.FindString(str)
	result = strings.TrimFunc(result, TrimFunc)
	return result[len(pre):]
}

func TrimFunc(r rune) bool {
	if r == ' ' || r == '"' {
		return true
	}
	return false
}

type SK struct {
	SyncKey SyncKey `json:"SyncKey"`
}

type SyncKey struct {
	Count int     `json:"Count"`
	List  []*List `json:"List"`
}

type List struct {
	Key int `json:"Key"`
	Val int `json:"Val"`
}

func GetSynckey(js string) (string, SK) {
	var str string
	var sk SK
	json.Unmarshal([]byte(js), &sk)

	for _, v := range sk.SyncKey.List {
		str += fmt.Sprintf("|%v_%v", v.Key, v.Val)
	}
	return str[1:], sk
}

type UsersList struct {
	UserList []*User `json:"MemberList"`
	MySelf   User    `json:"User"`
}

type User struct {
	UserName   string `json:"UserName"`
	NickName   string `json:"NickName"`
	RemarkName string `json:"RemarkName"`
}

func (userList *UsersList) GetUserName(_name string) string {
	for _, v := range userList.UserList {
		if v.RemarkName == _name {
			return v.UserName
		}
		if v.NickName == _name {
			return v.UserName
		}
	}
	return ""
}

func (userList *UsersList) GetName(_userName string) string {
	for _, v := range userList.UserList {
		if v.UserName == _userName {
			if v.RemarkName != "" {
				return v.RemarkName
			}
			return v.NickName
		}
	}
	return _userName
}

func GetMe(js string) User {
	var userList UsersList
	err := json.Unmarshal([]byte(js), &userList)
	if err != nil {
		panic(err)
	}
	userList.MySelf.RemarkName = "我"
	return userList.MySelf
}

func GetUsers(js string) UsersList {
	var userList UsersList
	err := json.Unmarshal([]byte(js), &userList)
	if err != nil {
		panic(err)
	}
	return userList
}

type Msg struct {
	MsgList []*MsgInfo `json:"AddMsgList"`
}

type MsgInfo struct {
	MsgId        string `json:"MsgId"`
	FromUserName string `json:"FromUserName"`
	ToUserName   string `json:"ToUserName"`
	MsgType      int    `json:"MsgType"`
	Content      string `json:"Content"`
}

func GetMsg(js string) []*MsgInfo {
	var msg Msg
	err := json.Unmarshal([]byte(js), &msg)
	if err != nil {
		panic(err)
	}
	return msg.MsgList
}
